package com.tensquare.friend.controller;

import com.tensquare.friend.client.FriendClient;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("friend")
public class FriendController {

    @Autowired
    private FriendService friendService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private NoFriendService noFriendService;
    @Autowired
    private FriendClient friendClient;
    @Autowired
    private RedisTemplate redisTemplate;

    //添加好友或非好友
    @PutMapping("like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type) {
        //获取权限
        Claims user = (Claims) request.getAttribute("user");
        System.out.println("user = " + user);
        //判断当前的claims是否为null
        if (user == null) {
            return new Result(false, StatusCode.ACCESSERROR, "无权访问");
        } else {
            if (type.equals("1")) {
                int count = friendService.addFriend(user.getId(), friendid, type);
                String userid=user.getId();
                String friendid1 = (String) redisTemplate.opsForValue().get(userid);
                System.out.println("friendid1 = " + friendid1);
                if(friendid1==null||!friendid1.equals(friendid)){
                    //增加自己的关注数
                    friendClient.addfollow(user.getId(),1);
                    //增加对方的粉丝数
                    friendClient.addfans(friendid,1);
                }
                redisTemplate.opsForValue().set(userid,friendid);
                if(count==0){
                    return new Result(false,StatusCode.REPERROR,"不能重复添加好友");
                }
            }else {
                //添加非好友
                noFriendService.addFriend(user.getId(),friendid);
            }
        }
        return  new Result(true,StatusCode.OK,"好友添加成功");
    }

}
